﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Xml.Linq;
using Ionic.Zip;
using System.Net;
using System.IO;
using MyDownloader.App;

namespace Theme_Creator
{
    public partial class Form1 : Form
    {
        int count = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            fillCombobox();
            submit.Enabled = false;
            webKitBrowser1.Navigate("memorykidz.henriarends.nl");
            submit.Enabled = false;

        }
        protected static String nameSchool;
        public static String getNameSchool()
        {
            return nameSchool;
        }
        protected static String passWord;
        public static String getPassWord()
        {
            return passWord;
        }
        protected static String schoolID;
        public static String getSchoolID()
        {
            return schoolID;
        }
        private db db;
        private void login()
        {
            db = new db();
            using (Login frm = new Login())
            {
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    nameSchool = frm.nameSchool;
                    passWord = frm.Password;
                    schoolID = frm.schoolID;
                    List<string> list;
                    list = db.Select();
                    if (frm.nameSchool == list[1] && frm.Password == list[2] && frm.schoolID == list[0])
                    {
                        frm.Close();
                   } 
                    else
                    {
                        MessageBox.Show("Ongeldige gegevensinvoer geconstateerd.");
                        login();
                    }
                }
                else
                {
                    Application.Exit();
                }
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            login();
            base.OnLoad(e);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

public void Upload(string filename, string ftpServerIP, string 
ftpUserID, string ftpPassword)
         {
             FileInfo fileInf = new FileInfo(filename);
             string uri = "ftp://" +
             ftpServerIP + "/" + fileInf.Name;
             FtpWebRequest reqFTP;
             reqFTP =
             (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + 
ftpServerIP +
             "/" + fileInf.Name));
             reqFTP.Credentials = new NetworkCredential(ftpUserID, 
ftpPassword);
             reqFTP.KeepAlive = false;
             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
             reqFTP.UseBinary = true;
             reqFTP.ContentLength = fileInf.Length;
             int buffLength = 2048;
             byte[] buff = new byte[buffLength];
             int contentLen;
             FileStream fs = fileInf.OpenRead();
             try
             {
                 Stream strm = reqFTP.GetRequestStream();
                 contentLen = fs.Read(buff, 0, buffLength);
                 while (contentLen != 0)
                 {
                     strm.Write(buff, 0, contentLen);
                     contentLen = fs.Read(buff, 0, buffLength);
                 }
                 strm.Close();
                 fs.Close();
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message, "Upload Error");
             }
         }

        private void browse_Click(object sender, EventArgs e)
        {

        }
        private void fillCombobox()
        {
            List<string> list = new List<string>();
            list.Add("Groep 3-4");
            list.Add("Groep 5-6");
            list.Add("Groep 7-8");
            groupSelect.DataSource = list;
        }
        int sizeH = 117;
        int sizeW = 162;
        private void browse_Click_1(object sender, EventArgs e)
        {
            dlg.Filter = "Supported Files(*.png;)|*.png;";
            dlg.Multiselect = true;


            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.FileNames.Length == 2)
                {
                    foreach (string FileName in dlg.FileNames)
                    {
                        Bitmap img = new Bitmap(dlg.FileName);
                        var imageHeight = img.Height;
                        var imageWidth = img.Width;
                        if (imageHeight == sizeH && imageWidth == sizeW)
                        {
                            count = count + 1;
                            listBox1.Items.Add(FileName);
                            if (count == 36)
                            {
                                submit.Enabled = true;
                                browse.Enabled = false;
                            }
                        }
                        else
                        {
                            MessageBox.Show("Formaat van de afbeelding is incorrect, deze moet hoogte: " + sizeH + " en breedte: "+sizeW + " zijn.");
                        }
                    }
                }
                else if (dlg.FileNames.Length < 2)
                {
                    MessageBox.Show("Er zijn teweinig afbeeldingen geselecteerd. Graag 2 afbeeldingen kiezen.");
                }
                else if (dlg.FileNames.Length > 2)
                {
                    MessageBox.Show("Er zijn teveel afbeeldingen geselecteerd. Graag 2 afbeeldingen kiezen.");
                }
                else
                {
                    MessageBox.Show("Unexpected error!");
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            
        }
        String location = "/themeWorkDir";
        private void submit_Click(object sender, EventArgs e)
        {
            
            // maak XML doc aan en save deze in .
            startXdoc();
            ZipFile zip = new ZipFile();
            // a = image counter voor filename
            int a = 0;
            //index bijhouden min 1, tel af.
            for (int i = listBox1.Items.Count - 1; i >= 0; i--)
            {  
                   if (i >= 27)
                   {
                        a = a + 1;
                        zip.AddFile(listBox1.Items[i].ToString(), "").FileName = titel.Text + "0" + a + ".png";
                   }

                   else
                   {
                        a = a + 1;
                        zip.AddFile(listBox1.Items[i].ToString(), "").FileName = titel.Text + a + ".png";
                   }
            }
                zip.AddFile(titel.Text + ".xml", "");
            // Save zip file
                zip.Save(location + titel.Text + ".zip");
                String tempSchoolID;
                if (openbaar.Checked == true)
                {
                    tempSchoolID = "3";
                }
                else
                {
                    tempSchoolID = schoolID;
                }
                db.Insert(titel.Text, auteur.Text, groupSelect.Text, tempSchoolID);
                Upload(location + titel.Text, "ftp.henriarends.nl/Upload", "memorykidz@henriarends.nl", "Geheim12");
        }

        // create en save the XML file, methode
        private void startXdoc()
        {

            if (schoolGebonden.Checked == true)
            {

                XDocument d = new XDocument
                    (
                    new XElement("Thema",
                    new XElement("Title", titel.Text),
                    new XElement("Auteur", auteur.Text),
                    new XElement("Groep", groupSelect.Text),
                    new XElement("Rechten", schoolGebonden.Text)
                                )
                    );
                d.Declaration = new XDeclaration("1.0", "utf-8", "true");
                Console.WriteLine(d);
                d.Save(titel.Text + ".xml");
            }

            else if (openbaar.Checked == true)
            {
                XDocument d = new XDocument
                    (
                    new XElement("Thema",
                    new XElement("Title", titel.Text),
                    new XElement("Auteur", auteur.Text),
                    new XElement("Groep", groupSelect.Text),
                    new XElement("Rechten", openbaar.Text)
                                )
                    );
                d.Declaration = new XDeclaration("1.0", "utf-8", "true");
                Console.WriteLine(d);
                d.Save(titel.Text + ".xml");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Afbeeldingen moeten voldoen aan vaste maten, deze moet hoogte: " + sizeH + " en breedte: " + sizeW + " zijn.");
        }

        private void webKitBrowser1_Load(object sender, EventArgs e)
        {
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            browse.Enabled = true;
            submit.Enabled = false;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.ShowDialog();
            dialog.Filter = "Supported Files(*.zip;)|*.zip;";
            dialog.Multiselect = false;

            label6.Text = dialog.FileName;
            String[] zipname = label6.Text.Split('\\');
            int i = zipname.Count();
            String[] name = zipname[i - 1].Split('.');
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string zipToUnpack = label6.Text;
            //string unpackDirectory = "C:\\users\\henri\\Desktop\\";
            string unpackDirectory = "D:\\Code MemoryKidz TNS Final\\DEBUG\\MemoryKidz\\bin\\WindowsGL\\Debug\\Content\\Textures\\Themes";
            using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
            {
                // here, we extract every entry, but we could extract conditionally
                // based on entry name, size, date, checkbox status, etc.  
                foreach (ZipEntry file in zip1)
                {
                    file.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
                }
            }
            MessageBox.Show("Finished");
        }
    }
}

